package com.hangzhou.welbeing.welbeinginstrument.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hangzhou.welbeing.welbeinginstrument.R;
import com.hangzhou.welbeing.welbeinginstrument.base.MyApplication;
import com.hangzhou.welbeing.welbeinginstrument.bean.WeChatLoginBean;
import com.hangzhou.welbeing.welbeinginstrument.config.RBConstants;
import com.hangzhou.welbeing.welbeinginstrument.utils.Utils;
import com.mob.tools.utils.UIHandler;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 时间 2017 年 08 月 18.
 * 作者 Administrator  刘传华
 * 公司 杭州惟君医疗科技有限公司
 * 包名 com.hangzhou.welbeing.pregnant.welbeing_pregnant.activity
 * 工程名 welbeing_pregnant
 *
 * @desc 入口界面是闪屏界面过后第一个界面
 * @desc 全新的框架 全新的插件
 * @desc 登录——注册
 */
public class EntranceActivity extends Activity  implements  Handler.Callback, PlatformActionListener {
    private static final String TAG = "EntranceActivity";
    @Bind(R.id.activity_entrance_iv_logo)
    ImageView activityEntranceIvLogo;
    @Bind(R.id.activity_entrance_rl_login)
    RelativeLayout activityEntranceRlLogin;
    @Bind(R.id.activity_entrance_rl_registration)
    RelativeLayout activityEntranceRlRegistration;
    @Bind(R.id.activity_entrance_iv_WeChat)
    ImageView activityEntranceIvWeChat;
    @Bind(R.id.activity_entrance_iv_QQ)
    ImageView activityEntranceIvQQ;
    @Bind(R.id.activity_entrance_ll_third_party)
    RelativeLayout activityEntranceLlThirdParty;
    private static final int MSG_USERID_FOUND = 1;
    private static final int MSG_LOGIN = 2;
    private static final int MSG_AUTH_CANCEL = 3;
    private static final int MSG_AUTH_ERROR = 4;
    private static final int MSG_AUTH_COMPLETE = 5;
    private boolean is_or_no_login;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_entrance);
        ButterKnife.bind(this);
        Utils.setStatusBar(this,false,false);
        Utils.setStatusTextColor(true,this);
    }
    @OnClick({R.id.activity_entrance_rl_login, R.id.activity_entrance_rl_registration, R.id.activity_entrance_iv_WeChat, R.id.activity_entrance_iv_QQ})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.activity_entrance_rl_login:
                Intent intent = new Intent(EntranceActivity.this,LoginActivity.class);
                startActivity(intent);
                finish();
                overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
                break;
            case R.id.activity_entrance_rl_registration:
                Intent intent2 = new Intent(EntranceActivity.this,RegistrationActivity.class);
                startActivity(intent2);
                finish();
                overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
                break;
            case R.id.activity_entrance_iv_WeChat:
                authorize(new Wechat());
                break;
            case R.id.activity_entrance_iv_QQ:
                authorize(new QQ());
                break;
        }
    }
    //执行授权,获取用户信息  isValid()
    private void authorize(Platform plat) {
        if (plat.isAuthValid()) {
            String userId = plat.getDb().getUserId();
            if (!TextUtils.isEmpty(userId)) {
                UIHandler.sendEmptyMessage(MSG_USERID_FOUND, this);
                login(plat.getName(), userId, null);
                return;
            }
        }
        plat.setPlatformActionListener(EntranceActivity.this);
        //true不使用SSO授权，false使用SSO授权
        plat.SSOSetting(false);
        plat.showUser(null);
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case MSG_USERID_FOUND: {
                //Toast.makeText(this, R.string.userid_found, Toast.LENGTH_SHORT).show();
            }
            break;
            case MSG_LOGIN: {
                String text = getString(R.string.logining, msg.obj);
                Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
            }
            break;
            case MSG_AUTH_CANCEL: {
                Toast.makeText(this, R.string.auth_cancel, Toast.LENGTH_SHORT).show();
            }
            break;
            case MSG_AUTH_ERROR: {
                Toast.makeText(this, R.string.auth_error, Toast.LENGTH_SHORT).show();
            }
            break;
            case MSG_AUTH_COMPLETE: {
                Toast.makeText(this, R.string.auth_complete, Toast.LENGTH_SHORT).show();
            }
            break;
        }
        return false;
    }

    @Override
    public void onComplete(Platform platform, int action, HashMap<String, Object> hashMap) {
        if (action == Platform.ACTION_USER_INFOR) {
            //登录成功,获取需要的信息
            UIHandler.sendEmptyMessage(MSG_AUTH_COMPLETE, this);
            login(platform.getName(), platform.getDb().getUserId(), hashMap);
            String openid = platform.getDb().getUserId() + "";
            String gender = platform.getDb().getUserGender();
            String head_url = platform.getDb().getUserIcon();
            String nickname = platform.getDb().getUserName();


            if(platform.getName().equals("QQ")){
                submitQQLogin(platform.getDb().getUserId(),"qq");
            }else if(platform.getName().equals("Wechat")){
                submitWeChatLogin(platform.getDb().getUserId(),"qq");
            }
        }
    }


    @Override
    public void onError(Platform platform, int action, Throwable throwable) {
        if(action==Platform.ACTION_USER_INFOR){
            UIHandler.sendEmptyMessage(MSG_AUTH_ERROR,this);
        }
        throwable.printStackTrace();
    }

    @Override
    public void onCancel(Platform platform, int action) {
        if (action == Platform.ACTION_USER_INFOR) {
            UIHandler.sendEmptyMessage(MSG_AUTH_CANCEL, this);
        }
    }
    //发送登陆信息
    private void login(String plat, String userId, HashMap<String, Object> userInfo) {
        Message msg = new Message();
        msg.what = MSG_LOGIN;
        msg.obj = plat;
        UIHandler.sendMessage(msg, this);
    }
    /**
     * @desc qq登录
     * */
    private void submitQQLogin(final String userId, final String qq) {
        OkHttpUtils
                .post()
                .url(RBConstants.SERVER_URL+RBConstants.OTHER_LOGIN)
                .addParams(qq+"",userId)
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String stringparseNetworkResponse = response.body().string();
                        Gson gson = new Gson();
                        Log.e(TAG,"parseNetworkResponse========"+stringparseNetworkResponse);
                        final WeChatLoginBean weChatLoginBean =   gson.fromJson(stringparseNetworkResponse,WeChatLoginBean.class);
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    if(weChatLoginBean.errorCode == 200){
                                        SharedPreferences sp = getSharedPreferences("second_app_internal_data", 0);
                                        SharedPreferences.Editor edit = sp.edit();
                                        edit.putString("qq",userId);
                                        edit.commit();
                                        Intent intent = new Intent(EntranceActivity.this, BindingMobilePhoneNumberActivity.class);
                                        intent.putExtra("ID", userId);
                                        intent.putExtra("userNAME", qq);
                                        startActivity(intent);
                                        overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
                                    }else{
                                        Toast.makeText(EntranceActivity.this,weChatLoginBean.errorMessage,Toast.LENGTH_LONG).show();
                                    }

                                }
                            });
                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(EntranceActivity.this,"网咯异常",Toast.LENGTH_LONG).show();
                    }
                    @Override
                    public void onResponse(Object response, int id) {}
                });
    }
    /**
     * @desc 微信登录
     * */
    private void submitWeChatLogin(final String userId, final String qq) {
        OkHttpUtils
                .post()
                .url(RBConstants.SERVER_URL+RBConstants.OTHER_LOGIN)
                .addParams(qq+"", userId)
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String stringparseNetworkResponse = response.body().string();
                        Gson gson = new Gson();
                        Log.e(TAG,"parseNetworkResponse========"+stringparseNetworkResponse);
                        final WeChatLoginBean weChatLoginBean =   gson.fromJson(stringparseNetworkResponse,WeChatLoginBean.class);
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    if(weChatLoginBean.errorCode == 200){
                                        SharedPreferences sp = getSharedPreferences("second_app_internal_data", 0);
                                        SharedPreferences.Editor edit = sp.edit();
                                        edit.putString("weixin",userId);
                                        edit.commit();

                                        Intent intent = new Intent(EntranceActivity.this, BindingMobilePhoneNumberActivity.class);
                                        intent.putExtra("ID", userId);
                                        intent.putExtra("userNAME", qq);
                                        startActivity(intent);
                                        overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
                                    }else{
                                        Toast.makeText(EntranceActivity.this,weChatLoginBean.errorMessage,Toast.LENGTH_LONG).show();
                                    }

                                }
                            });
                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(EntranceActivity.this,"网咯异常",Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });
    }

}
